﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cloud.Core.AuthUser;
using Cloud.Core.Bizlogic;
using Cloud.Core.Model;
using Cloud.Core.Model.Promotion;
using Cloud.Core.ModelSearch;
using Cloud.Core.Request.WebChat;
using Cloud.Core.Request.WebChat.PromotionsInsert;
using Cloud.Core.Response;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace Cloud.Core.Controllers.WebChat
{
    [Route("api/wx/[controller]")]
    [ApiController]
    public class PromotionsController : ControllerBase
    {
        private readonly CloudDataBase _context;
        private readonly ModOperate.Mod _thisModel = ModOperate.Mod.MBasicInfo;
        public PromotionsController ( CloudDataBase context )
        {
            _context = context;
        }
        /// <summary>
        /// 用户推广申请新增
        /// </summary>
        /// <param name="promotionUserRequest"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PromotionUserApply")]
        public async Task<JsonResponse<ulong>> PromotionUserApply ( PromotionUserRequest promotionUserRequest )
        {
            try
            {
                if (promotionUserRequest == null)
                {
                    return new JsonResponse<ulong>
                    {
                        Msg = "参数不合法",
                        Status = ResponseStatus.ParameterError
                    };
                }
                if (string.IsNullOrEmpty(promotionUserRequest.openId))
                {
                    return new JsonResponse<ulong>
                    {
                        Msg = "参数不合法",
                        Status = ResponseStatus.ParameterError
                    };
                }

            
                var list = await _context.PromotionUsers.Where(t => t.openId == promotionUserRequest.openId).ToListAsync();

                if (list.Count > 0)
                {
                    PromotionUsers PromotionUsersEntity = list.First();
                    PromotionUsersEntity.Status = 0;
                    PromotionUsersEntity.PromotionImgs = promotionUserRequest.PromotionImgs;
                    PromotionUsersEntity.PromotionAddress = promotionUserRequest.PromotionAddress;

                    _context.Set<PromotionUsers>().Update(PromotionUsersEntity);
                    int num = _context.SaveChanges();
                    if (num > 0)
                    {
                        return new JsonResponse<ulong>
                        {
                            Msg = "申请成功",
                            Status = ResponseStatus.Success,
                            Data = PromotionUsersEntity.Id
                        };
                    }
                    else
                    {
                        return new JsonResponse<ulong>
                        {
                            Msg = "申请失败",
                            Status = ResponseStatus.ParameterError
                        };
                    }
                }
                else
                {
                    var entity = new PromotionUsers
                    {
                        PromotionName = promotionUserRequest.PromotionName,
                        PromotionAddress = promotionUserRequest.PromotionAddress,
                        PromotionUserType = promotionUserRequest.PromotionUserType,
                        SiteInfoImgs = promotionUserRequest.SiteInfoImgs,
                        RealNameImgs = promotionUserRequest.RealNameImgs,
                        RealNameInfo = promotionUserRequest.RealNameInfo,
                        ContactNumber = promotionUserRequest.ContactNumber,
                        PromotionImgs = promotionUserRequest.PromotionImgs,
                        IsrtDt = DateTime.Now,
                        openId = promotionUserRequest.openId,
                        Status = 0
                    };
                    _context.Set<PromotionUsers>().Add(entity);
                    int num = await _context.SaveChangesAsync().ConfigureAwait(false);
                    if (num > 0)
                    {
                        return new JsonResponse<ulong>
                        {
                            Msg = "申请成功",
                            Status = ResponseStatus.Success,
                            Data = entity.Id
                        };
                    }
                    else
                    {
                        return new JsonResponse<ulong>
                        {
                            Msg = "申请失败",
                            Status = ResponseStatus.ParameterError
                        };
                    }
                }
            }
            catch (Exception ex)
            {
                return new JsonResponse<ulong>
                {
                    Msg = "申请失败",
                    Status = ResponseStatus.ParameterError
                };
            }

        }



        /// <summary>
        /// 用户地址新增
        /// </summary>
        /// <param name="promotionsUserAddressRequest"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PromotionUserAddressInsert")]
        public async Task<JsonResponse> PromotionUserAddressInsert ( PromotionsUserAddressRequest promotionsUserAddressRequest )
        {

            if (promotionsUserAddressRequest == null)
            {
                return new JsonResponse
                {
                    Msg = "参数不合法",
                    Status = ResponseStatus.ParameterError
                };
            }
            if (string.IsNullOrEmpty(promotionsUserAddressRequest.openId))
            {
                return new JsonResponse
                {
                    Msg = "参数不合法",
                    Status = ResponseStatus.ParameterError
                };
            }
            var entity = new PromotionsUserAddress
            {
                Description = promotionsUserAddressRequest.Description,
                latitude = promotionsUserAddressRequest.latitude,
                longitude = promotionsUserAddressRequest.longitude,
                Address = promotionsUserAddressRequest.Address,
                openId = promotionsUserAddressRequest.openId,
                IsrtDt = DateTime.Now

            }; ;
            _context.Set<PromotionsUserAddress>().Add(entity);
            int num = await _context.SaveChangesAsync().ConfigureAwait(false);
            if (num > 0)
            {
                return new JsonResponse
                {
                    Msg = "新增成功",
                    Status = ResponseStatus.Success
                };
            }
            else
            {
                return new JsonResponse
                {
                    Msg = "新增失败",
                    Status = ResponseStatus.ParameterError
                };
            }
        }


        /// <summary>
        /// 删除用户地址
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PromotionUserAddressDelete")]
        public async Task<JsonResponse> PromotionUserAddressDelete ( ulong id )
        {

            if (id <= 0)
            {
                return new JsonResponse<ulong>
                {
                    Msg = "参数不合法",
                    Status = ResponseStatus.ParameterError
                };
            }
            var model = await _context.PromotionsUserAddress.FindAsync(id);
            _context.PromotionsUserAddress.Remove(model);
            int num = await _context.SaveChangesAsync().ConfigureAwait(false);
            if (num > 0)
            {
                return new JsonResponse
                {
                    Msg = "删除成功",
                    Status = ResponseStatus.Success,

                };
            }
            else
            {
                return new JsonResponse
                {
                    Msg = "删除失败",
                    Status = ResponseStatus.ParameterError
                };
            }
        }



        /// <summary>
        /// 获取用户地址列表
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetPromotionUserAddressList")]
        public async Task<JsonResponse> GetPromotionUserAddressList ( string openId )
        {


            if (string.IsNullOrEmpty(openId))
            {
                return new JsonResponse
                {
                    Msg = "参数不合法",
                    Status = ResponseStatus.ParameterError
                };
            }
            var list = await _context.PromotionsUserAddress.Where(t => t.openId == openId).ToListAsync();

            return new JsonResponse<List<PromotionsUserAddress>>
            {
                Data = list,
                Msg = "获取成功",
                Status = ResponseStatus.Success
            };

        }


        /// <summary>
        /// 获取推广列表
        /// </summary>
        /// <param name="promotionsInsertRequest"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PromotionList")]
        public async Task<JsonResponse<List<Promotions>>> PromotionList ( PromotionListRequest promotionListRequest )
        {
            var list = await _context.Promotions.Where(t => t.PromotionUsersId == promotionListRequest.PromotionUsersId && t.openId == promotionListRequest.openId).ToListAsync();

            var join2 = list.Join(_context.PromotionsUserAddress,
                        pro => pro.PromoteLocation,//左表要连接的键
                        address => address.Id + "",//右表要连接的键
                        ( pro, address ) => new Promotions//返回的结果集
                        {
                            Id = pro.Id,
                            openId = pro.openId,
                            PromoteLocation = address.Address,
                            PromotionAmount = pro.PromotionAmount,
                            PromotionCount = pro.PromotionCount,
                            PromotionScope = pro.PromotionScope,
                            PromotionUsersId = pro.PromotionUsersId,
                            IsrtDt = pro.IsrtDt,
                            QuestionImgs = pro.QuestionImgs
                        }
                    ).OrderBy(t => t.IsrtDt).ToList();



            return new JsonResponse<List<Promotions>>
            {
                Data = join2,
                Msg = "获取成功",
                Status = ResponseStatus.Success
            };


        }

        /// <summary>
        /// 获取推广者实体
        /// </summary>
        /// <param name="promotionsInsertRequest"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PromotionUsersEntity")]
        public async Task<JsonResponse<PromotionUsers>> PromotionUsersEntity ( PromotionListRequest promotionListRequest )
        {
            var list = await _context.PromotionUsers.Where(t => t.openId == promotionListRequest.openId).ToListAsync();

            if (list.Count == 0)
            {
                return new JsonResponse<PromotionUsers>
                {
                    Data = null,
                    Msg = "获取成功",
                    Status = ResponseStatus.Success
                };
            }
            else
            {
                return new JsonResponse<PromotionUsers>
                {
                    Data = list[0],
                    Msg = "获取成功",
                    Status = ResponseStatus.Success
                };
            }



        }
        /// <summary>
        ///  新增推广信息
        /// </summary>
        /// <param name="promotionsInsertRequest"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PromotionInsert")]
        public async Task<JsonResponse> PromotionInsert ( PromotionsInsertRequest promotionsInsertRequest )
        {
            var PromotionUsersEntity = _context.PromotionUsers.Where(t => t.openId == promotionsInsertRequest.promotionsRequest.openId).First();
            if (PromotionUsersEntity == null)
            {
                return new JsonResponse
                {
                    Msg = "您不是商家，不允许发布推广，请注册商家",
                    Status = ResponseStatus.ParameterError
                };
            }
            else
            {
                if (PromotionUsersEntity.Status == 0)
                {
                    return new JsonResponse
                    {
                        Msg = "该商家审核尚未通过，不允许发布推广!",
                        Status = ResponseStatus.ParameterError
                    };
                }

            }
            if (promotionsInsertRequest == null || promotionsInsertRequest.promotionsRequest == null
                || promotionsInsertRequest.promotionsNewComerQuestionRequest == null
                || promotionsInsertRequest.promotionsNewComerAnswerRequests == null)
            {
                return new JsonResponse
                {
                    Msg = "参数不合法",
                    Status = ResponseStatus.ParameterError
                };
            }

            var entity = new Promotions
            {
                openId = promotionsInsertRequest.promotionsRequest.openId,
                PromotionUsersId = promotionsInsertRequest.promotionsRequest.PromotionUsersId,
                PromotionScope = promotionsInsertRequest.promotionsRequest.PromotionScope,
                PromoteLocation = promotionsInsertRequest.promotionsRequest.PromoteLocation,
                PromotionCount = promotionsInsertRequest.promotionsRequest.PromotionCount,
                QuestionImgs = promotionsInsertRequest.promotionsRequest.QuestionImgs,
                IsrtDt = DateTime.Now
            };

            _context.Set<Promotions>().Add(entity);
            int num = await _context.SaveChangesAsync().ConfigureAwait(false);
            if (num > 0)
            {

                var questionentity = new PromotionsNewComerQuestion
                {
                    PromotionsId = entity.Id,
                    QuestionId = promotionsInsertRequest.promotionsNewComerQuestionRequest.QuestionId,
                    IsrtDt = DateTime.Now
                };

                _context.Set<PromotionsNewComerQuestion>().Add(questionentity);
                int questionnum = await _context.SaveChangesAsync().ConfigureAwait(false);
                if (questionnum > 0)
                {
                    foreach (var request in promotionsInsertRequest.promotionsNewComerAnswerRequests)
                    {
                        var Answerentity = new PromotionsNewComerAnswer
                        {
                            NewComerQuestionId = questionentity.Id,
                            NewComerAnswer = request.NewComerAnswer,
                            IsRight = request.IsRight,
                            IsrtDt = DateTime.Now
                        };
                        _context.Set<PromotionsNewComerAnswer>().Add(Answerentity);
                        await _context.SaveChangesAsync().ConfigureAwait(false);
                    }
                }

                return new JsonResponse
                {
                    Msg = "添加成功",
                    Status = ResponseStatus.Success
                };
            }
            else
            {
                return new JsonResponse
                {
                    Msg = "添加失败",
                    Status = ResponseStatus.ParameterError
                };
            }
        }
        /// <summary>
        /// 新增抽奖红包
        /// </summary>
        /// <param name="luckyDrawRedEnvelopeInsertRequest"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("LuckyDrawRedEnvelopeInsert")]
        public async Task<JsonResponse> LuckyDrawRedEnvelopeInsert ( List<LuckyDrawRedEnvelopeInsertRequest> luckyDrawRedEnvelopeInsertRequest )
        {

            if (luckyDrawRedEnvelopeInsertRequest == null)
            {
                return new JsonResponse
                {
                    Msg = "参数不合法",
                    Status = ResponseStatus.ParameterError
                };
            }
            luckyDrawRedEnvelopeInsertRequest.ForEach(item =>
            {

                var entity = new LuckyDrawCoupon
                {
                    CouponName = "现金红包",
                    PromotionsId = item.PromotionsId,
                    CouponImgs = item.RedEnvelopeImgs,
                    CouponCount = item.RedEnvelopeCount,
                    CouponAmount = item.RedEnvelopeAmount,
                    LuckyDrawDate = item.LuckyDrawDate,
                    LuckyDrawCouponType = LuckyDrawCouponType.RedEnvelope,
                    IsrtDt = DateTime.Now
                };

                _context.Set<LuckyDrawCoupon>().Add(entity);




            });


            int num = await _context.SaveChangesAsync().ConfigureAwait(false);
            if (num > 0)
            {
                return new JsonResponse
                {
                    Msg = "添加成功",
                    Status = ResponseStatus.Success
                };
            }
            else
            {
                return new JsonResponse<int>
                {
                    Msg = "添加失败",
                    Status = ResponseStatus.ParameterError
                };
            }
        }
        /// <summary>
        /// 新增抽奖商品券
        /// </summary>
        /// <param name="luckyDrawGiftCouponInsertRequest"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("LuckyDrawGiftCouponInsert")]
        public async Task<JsonResponse> LuckyDrawGiftCouponInsert ( List<LuckyDrawGiftCouponInsertRequest> luckyDrawGiftCouponInsertRequest )
        {

            if (luckyDrawGiftCouponInsertRequest == null)
            {
                return new JsonResponse
                {
                    Msg = "参数不合法",
                    Status = ResponseStatus.ParameterError
                };
            }

            luckyDrawGiftCouponInsertRequest.ForEach(item =>
            {


                var entity = new LuckyDrawCoupon
                {
                    //CouponAmount = 1,
                    PromotionsId = item.PromotionsId,
                    CouponImgs = item.GiftCouponImgs,
                    CouponCount = item.GiftCouponCount,
                    CouponName = item.GiftCouponName,
                    LuckyDrawDate = item.LuckyDrawDate,
                    ExpirationDate = item.ExpirationDate,
                    LuckyDrawCouponType = LuckyDrawCouponType.GiftCoupon,
                    IsrtDt = DateTime.Now
                };

                _context.Set<LuckyDrawCoupon>().Add(entity);



            });



            int num = await _context.SaveChangesAsync().ConfigureAwait(false);
            if (num > 0)
            {
                return new JsonResponse
                {
                    Msg = "添加成功",
                    Status = ResponseStatus.Success
                };
            }
            else
            {
                return new JsonResponse<int>
                {
                    Msg = "添加失败",
                    Status = ResponseStatus.ParameterError
                };
            }
        }


        #region 获取字典信息
        /// <summary>
        /// HBED 红包额度 TGFW 推广范围    TGGS  推广个数
        /// </summary>
        /// <param name="Code"></param>
        /// <returns></returns>
        [Route("GetBaseDataInfoList")]
        [HttpGet]
        public async Task<JsonResponse<List<CodeMain>>> GetBaseDataInfoList ( string Code )
        {
            var list = await _context.Codemain.Where(t => t.Code == Code).OrderBy(t => t.Iorder).ToListAsync();
            return new JsonResponse<List<CodeMain>>
            {
                Data = list,
                Msg = "获取成功",
                Status = ResponseStatus.Success
            };


        }
        #endregion
        /// <summary>
        /// 新增抽奖折扣券
        /// </summary>
        /// <param name="luckyDrawDiscountCouponInsertRequest"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("LuckyDrawDiscountCouponInsert")]
        public async Task<JsonResponse> LuckyDrawDiscountCouponInsert ( List<LuckyDrawDiscountCouponInsertRequest> luckyDrawDiscountCouponInsertRequest )
        {

            if (luckyDrawDiscountCouponInsertRequest == null)
            {
                return new JsonResponse
                {
                    Msg = "参数不合法",
                    Status = ResponseStatus.ParameterError
                };
            }

            luckyDrawDiscountCouponInsertRequest.ForEach(item =>
            {

                var entity = new LuckyDrawCoupon
                {
                    CouponName = "折扣券",
                    PromotionsId = item.PromotionsId,
                    CouponImgs = item.DiscountCouponImgs,
                    CouponCount = item.DiscountCouponCount,
                    CouponAmount = item.DiscountCouponAmount,
                    LuckyDrawDate = item.LuckyDrawDate,
                    ExpirationDate = item.ExpirationDate,
                    LuckyDrawCouponType = LuckyDrawCouponType.DiscountCoupon,
                    IsrtDt = DateTime.Now
                };

                _context.Set<LuckyDrawCoupon>().Add(entity);


            });
            int num = await _context.SaveChangesAsync().ConfigureAwait(false);
            if (num > 0)
            {
                return new JsonResponse
                {
                    Msg = "添加成功",
                    Status = ResponseStatus.Success
                };
            }
            else
            {
                return new JsonResponse<int>
                {
                    Msg = "添加失败",
                    Status = ResponseStatus.ParameterError
                };
            }
        }
        /// <summary>
        /// 新增抽奖现金
        /// </summary>
        /// <param name="luckyDrawCashCouponInsertRequest"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("LuckyDrawCashCouponInsert")]
        public async Task<JsonResponse> LuckyDrawCashCouponInsert ( List<LuckyDrawCashCouponInsertRequest> luckyDrawCashCouponInsertRequest )
        {

            if (luckyDrawCashCouponInsertRequest == null)
            {
                return new JsonResponse
                {
                    Msg = "参数不合法",
                    Status = ResponseStatus.ParameterError
                };
            }


            luckyDrawCashCouponInsertRequest.ForEach(item =>
            {

                var entity = new LuckyDrawCoupon
                {
                    CouponName = "现金券",
                    PromotionsId = item.PromotionsId,
                    CouponImgs = item.CashCouponImgs,
                    CouponCount = item.CashCouponCount,
                    CouponAmount = item.CashCouponAmount,
                    LuckyDrawDate = item.LuckyDrawDate,
                    ExpirationDate = item.ExpirationDate,
                    LuckyDrawCouponType = LuckyDrawCouponType.CashCoupon,

                    IsrtDt = DateTime.Now
                };

                _context.Set<LuckyDrawCoupon>().Add(entity);



            });

            int num = await _context.SaveChangesAsync().ConfigureAwait(false);
            if (num > 0)
            {
                return new JsonResponse
                {
                    Msg = "添加成功",
                    Status = ResponseStatus.Success
                };
            }
            else
            {
                return new JsonResponse<int>
                {
                    Msg = "添加失败",
                    Status = ResponseStatus.ParameterError
                };
            }
        }



    }
}
